package com.example.content.fragment.main

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.example.content.*
import com.example.content.activity.SettingActivity
import com.example.content.adapter.viewpager.HomePagerAdapter
import com.example.content.databinding.FragmentMyBinding
import com.example.content.ext.convertUrl
import com.example.content.fragment.BaseMvvmFragment
import com.example.content.fragment.me.userproduct.UserProductFragment
import com.example.content.manager.ActivityMgr
import com.example.content.manager.GlideEngine
import com.example.content.manager.GlobalMgr
import com.example.content.repository.bean.UserInfo
import com.example.content.viewmodule.login.TokenStore
import com.example.content.viewmodule.main.CommonHomeViewModel
import com.example.content.views.ChangeBgPopup
import com.example.content.views.MySettingPopup
import com.example.content.views.MySharePopup
import com.example.content.views.ShareMyCardPopup
import com.example.core.extensions.showToast
import com.google.android.material.appbar.AppBarLayout
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.huantansheng.easyphotos.setting.Setting
import kotlin.math.abs

class MeFragment : BaseMvvmFragment<FragmentMyBinding, CommonHomeViewModel>() {

    private lateinit var sharePopup: MySharePopup
    private lateinit var changeBg:ChangeBgPopup
    private lateinit var settingPopup: MySettingPopup
    private lateinit var shareCardPopup: ShareMyCardPopup
    private val tabTitles = arrayOf("视频", "美图", "喜欢")
    private val fragments = mutableListOf<Fragment>()
    private lateinit var viewPagerAdapter: HomePagerAdapter
    private var userInfo:UserInfo?=null
    private var dealThumbUp = false

    override fun initView() {
        sharePopup = context?.let { MySharePopup(it) }!!
        shareCardPopup = context?.let { ShareMyCardPopup(it) }!!
        sharePopup.popupGravity = Gravity.BOTTOM
        val shareFriends = sharePopup.contentView?.findViewById<View>(R.id.share_friends)
        shareFriends?.setOnClickListener {
            shareCardPopup.showPopupWindow()
            sharePopup.dismiss()
        }
        val shareRules = sharePopup.contentView?.findViewById<View>(R.id.share_rules)
        shareRules?.setOnClickListener {
            context?.showToast("分享规则")
            sharePopup.dismiss()
        }
        val cancel = sharePopup.contentView?.findViewById<View>(R.id.share_cancel)
        cancel?.setOnClickListener{
            sharePopup.dismiss()
        }
        settingPopup = context?.let { MySettingPopup(it) }!!
        settingPopup.popupGravity = Gravity.BOTTOM
        val setting = settingPopup.contentView?.findViewById<View>(R.id.setting)
        setting?.setOnClickListener {
            startActivity(Intent(context, SettingActivity::class.java))
            settingPopup.dismiss()
        }
        val settingCancel = settingPopup.contentView?.findViewById<View>(R.id.share_cancel)
        settingCancel?.setOnClickListener {
            settingPopup.dismiss()
        }

        changeBg = ChangeBgPopup(context!!)
        changeBg.popupGravity = Gravity.BOTTOM
        val changeBgBtn = changeBg.contentView.findViewById<View>(R.id.change_bg)
        changeBgBtn.setOnClickListener {
            EasyPhotos.createAlbum(this, true, GlideEngine)
                .setFileProviderAuthority("com.example.pvshow.fileprovider")
                .setCount(1)
                .setCameraLocation(Setting.LIST_FIRST)
                .start(CODE_BG_IMG)
            changeBg.dismiss()
        }
        val changeBgCancel = changeBg.contentView.findViewById<View>(R.id.change_cancel)
        changeBgCancel.setOnClickListener {
            changeBg.dismiss()
        }

        fragments.add(UserProductFragment(USER_VIDEO))
        fragments.add(UserProductFragment(USER_PHOTO))
        fragments.add(UserProductFragment(USER_LIKE))

        //初始化tab
        viewPagerAdapter = HomePagerAdapter(childFragmentManager, fragments, tabTitles)
        dataBinding.viewPager.adapter = viewPagerAdapter
        dataBinding.tabLayout.setViewPager(dataBinding.viewPager, tabTitles)
    }

    override fun queryData() {
        viewModel.getUserInfo()
    }

    override fun initListener() {
//        dataBinding.changeBgImg.setOnClickListener {
////            sharePopup.showPopupWindow()
//
//        }

        dataBinding.personalBg.setOnClickListener {
            changeBg.showPopupWindow()
        }
        dataBinding.meMenu.setOnClickListener {
            settingPopup.showPopupWindow()
        }
        dataBinding.follow.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(KEY_FRAGMENT, ME_FOLLOWERS)
            bundle.putInt(FOLLOWERS_TYPE, MY_FOLLOW)
            ActivityMgr.startFragment(bundle)
        }
        dataBinding.fans.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(KEY_FRAGMENT, ME_FOLLOWERS)
            bundle.putInt(FOLLOWERS_TYPE, MY_FANS)
            ActivityMgr.startFragment(bundle)
        }
        dataBinding.myCoinCard.setOnClickListener {
            ActivityMgr.startFragment(ME_MY_COIN_TYPE)
        }
        dataBinding.vipOpenTip.setOnClickListener {
            ActivityMgr.startFragment(ME_VIP_PAGE_TYPE)
        }
        dataBinding.editUserInfo.setOnClickListener {
            ActivityMgr.startFragment(ME_EDIT_USER_INFO_TYPE)
        }
        dataBinding.appBarLayout.addOnOffsetChangedListener(AppBarChangeListener())

        viewModel.followersData.observe(this, {
            if (it.isNotEmpty()) {
                val data = it[0]
                dealUserInfo(data)
                userInfo = data
            }
        })
        GlobalMgr.userInfo.observe(this, {
//            Glide.with(this).load(it.avatar.convertUrl()).into(dataBinding.ivHead)
//            dataBinding.nickName.text = it.nickname
//            dataBinding.signature.text = it.signature
//            if (it.gender == SEX_MAN) {
//                dataBinding.sexType.setImageResource(R.drawable.ic_man)
//            } else {
//                dataBinding.sexType.setImageResource(R.drawable.ic_female)
//            }
//            val location = it.address.substring(it.address.indexOf("-") + 1)
//            dataBinding.locationName.text = location

            viewModel.getUserInfo()
        })
        GlobalMgr.follow.observe(this, {
            queryData()
        })
        GlobalMgr.thumbUp.observe(this, {
            dealThumbUp = true
            queryData()
        })
    }

    private fun dealUserInfo(data: UserInfo) {
        if (dealThumbUp) {
            tabTitles[2] = "喜欢(${data.user_like_num})"
            dataBinding.tabLayout.setTitle(tabTitles)
            dataBinding.tabLayout.notifyDataSetChanged()
            dealThumbUp = false
            return
        }
        Glide.with(this).load(data.avatar).into(dataBinding.ivHead)
        if (data.user_pics.isNotEmpty()) {
            Glide.with(this).load(data.user_pics[0].convertUrl()).placeholder(R.drawable.personal_detail_bg).into(dataBinding.personalBg)
        }
        dataBinding.nickName.text = data.nickname
        dataBinding.signature.text = data.signature
        if (data.gender == SEX_MAN) {
            dataBinding.sexType.setImageResource(R.drawable.ic_man)
        } else {
            dataBinding.sexType.setImageResource(R.drawable.ic_female)
        }
        dataBinding.followNum.text = data.follow_num.toString()
        dataBinding.fansNum.text = data.fans_num.toString()
        dataBinding.likeNum.text = data.liked_num.toString()
        val location = data.address.substring(data.address.indexOf("-") + 1)
        dataBinding.locationName.text = location
        tabTitles[0] = "视频(${data.user_video_num})"
        tabTitles[1] = "美图(${data.user_photo_num})"
        tabTitles[2] = "喜欢(${data.user_like_num})"
        dataBinding.viewPager.adapter = HomePagerAdapter(childFragmentManager, fragments, tabTitles)
        dataBinding.tabLayout.setViewPager(dataBinding.viewPager, tabTitles)
        TokenStore.setSexType(data.gender)
    }

    override fun getLayoutId() = R.layout.fragment_my

    inner class AppBarChangeListener : AppBarLayout.OnOffsetChangedListener {
        override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
            val totalRange = dataBinding.appBarLayout.totalScrollRange
            val factor = abs(verticalOffset.toFloat()).div(totalRange)
            Log.e("chaknaoffset", "verticalOffset: ${verticalOffset}, totalScrollRange: ${totalRange}, factor: $factor")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CODE_BG_IMG && data != null) {
            val images = data.getParcelableArrayListExtra<Photo>(EasyPhotos.RESULT_PHOTOS)
            if (images != null && images.isNotEmpty()) {
                context?.let { Glide.with(it).load(images[0].path).into(dataBinding.personalBg) }
                userInfo?.let { viewModel.modifyUserInfo(it, listOf(images[0].path)) }
            }
        }
    }

    companion object {

        const val CODE_BG_IMG = 10001

        @JvmStatic
        fun newInstance() = MeFragment()
    }

    override fun getViewModuleClass(): Class<CommonHomeViewModel> {
        return CommonHomeViewModel::class.java
    }
}